<template>
  <el-row :gutter="20">
    <el-col :sm="2" class="hidden-xs-only" style="opacity:0;">左侧占位</el-col>
    <el-col :xs="24" :sm="20">
      <el-container style="opacity: 0.9;display: block" class="message">
        <el-card class="animate__animated animate__fadeInLeft publish">
          <div class="author">
            <el-avatar v-if="token===null || token === undefined" :src="default_avatar" size="large"></el-avatar>
            <el-avatar v-else :src="avatar" size="large"></el-avatar>
            <div>
              <div class="nkname">
                <span> 欢迎 </span>
                <span class="name" v-if="token==null">匿名用户</span>
                <span class="name" v-else>{{ name }} </span>
              </div>
            </div>
          </div>
          <el-form :model="messageForm" :rules="messageFormRules" ref="messageFormRef">
            <el-form-item prop="content">
              <el-input @blur="blur" :rows="5" v-model="messageForm.content" type="textarea" maxlength="100"
                        show-word-limit placeholder="请输入你的留言"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-row>
                <el-col :span="12" style="text-align: left">
                  <Emoji @output="output"></Emoji>
                </el-col>
                <el-col :span="12" style="text-align: right">
                  <el-button type="primary" @click="publish">点击发表</el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>

          <div v-if="false" class="elementCollapse">
            <div class="collapseHeader">
              <el-collapse-transition>
                <div v-show="show" class="collapseHeaderBox">
                  <el-form :model="messageOtherForm" label-width="80px">
                    <el-form-item label="协助人" prop="parentId">
                      <el-input
                        v-model="messageOtherForm.content"
                        type="textarea" maxlength="100"
                        show-word-limit placeholder="请输入你的留言">
                      </el-input>
                    </el-form-item>
                  </el-form>
                </div>
              </el-collapse-transition>
              <div style="margin-top: 15px" class="collapseBtn" @click="show = !show">
                {{ show ? '收起' : '展开' }}
              </div>
            </div>
          </div>

        </el-card>

        <el-card v-if="messageList.length>0" class="animate__animated animate__fadeInLeft">
          <div slot="header" class="clearfix">
            <span>最新记录</span>
          </div>
          <comment :comments="messageList" @replyConfirm="commitComment"></comment>
          <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize" @pagination="getMessageList"
          />
        </el-card>
      </el-container>
    </el-col>
    <el-col :sm="2" class="hidden-xs-only" style="opacity:0;">右侧占位</el-col>
    <!-- 设置底部距离的 -->
    <el-backtop :bottom="60">
      <div style="
            height: 50px;
            width: 50px;
            background-color: rgba(240,239,241,1);
            box-shadow: 0 0 6px rgba(0,0,0, .12);
            text-align: center;
            line-height: 40px;
            border-radius:2px;
            color: #1989fa;
          "
      >
        <svg-icon icon-class="top"/>
      </div>
    </el-backtop>
  </el-row>
</template>

<script>
import {
  mapGetters
} from 'vuex'
import {
  getToken
} from '@/utils/auth'
import {
  cmsListMessage,
  cmsAddMessage
} from '@/api/cms/message'
import comment from './messages.vue'
import Emoji from '@/components/Emoji'

export default {
  components: {
    // Transition,
    comment,
    // textOverflow,
    Emoji
  },
  name: 'message',
  data() {
    return {
      picList: [],
      default_avatar: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
      editing: false,
      show: false,
      messageList: [],
      // userInfo: null,
      message: {
        userId: -1,
        content: ''
      },
      messageForm: {},
      messageOtherForm: {},
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        parentId: null,
        mainId: null,
        likeNum: null,
        content: null,
        type: null,
        blogId: null,
        userId: null,
        delFlag: null,
        createBy: null
      },
      messageFormRules: {
        content: [{
          min: 0,
          max: 100,
          message: '留言内容不超过100字！'
        }]
      },
      cursorIndexStart: null,//光标选中开始的位置
      cursorIndexEnd: null//光标选中结束的位置
    }
  },
  created() {
    this.getMessageList()
    this.reset()
    // console.log(this.token)
  },
  updated: function() {
    this.$nextTick(function() {
      // 仅在整个视图都被渲染之后才会运行的代码
      this.to()
    })
  },
  computed: {
    ...mapGetters([
      'token',
      'avatar',
      'name'
    ])
  },
  methods: {
    // 表单重置
    reset() {
      this.messageForm = {
        id: null,
        parentId: null,
        mainId: null,
        likeNum: null,
        content: null,
        type: null,
        blogId: null,
        userId: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm('messageForm')
    },
    // 留言发表
    publish() {
      let token = getToken()
      this.$refs.messageFormRef.validate(async valid => {
        if (!valid) return
        if (this.messageForm.content == null || this.messageForm.content === '') {
          this.$modal.msgError('留言内容不能为空！')
          return
        }
        if (token == null || token === '') {
          this.messageForm.createBy = '匿名用户'
          this.messageForm.type = '0'
        } else {
          this.messageForm.createBy = this.$store.getters.name
          this.messageForm.type = '0'
        }
        cmsAddMessage(this.messageForm).then(response => {
          this.$modal.msgSuccess('留言发表成功')
          this.reset()
          this.getMessageList()
        })
      })
    },
    /**
     * 提交评论
     */
    commitComment(value) {
      this.reset()
      this.messageForm.content = value.inputComment
      this.messageForm.parentId = value.id
      let token = getToken()
      this.$refs.messageFormRef.validate(async valid => {
        if (!valid) return
        if (this.messageForm.content == null || this.messageForm.content === '') {
          this.$modal.msgError('评论内容不能为空！')
          return
        }
        if (token == null || token === '') {
          this.messageForm.createBy = '匿名用户'
          this.messageForm.type = '1'
        } else {
          this.messageForm.createBy = this.$store.getters.name
          this.messageForm.type = '1'
        }
        cmsAddMessage(this.messageForm).then(response => {
          this.$modal.msgSuccess('评论发表成功')
          this.reset()
          this.getMessageList()
        })
      })
    },
    // 获取留言列表
    async getMessageList() {
      let token = getToken()

      if (token != null && token !== '') {
        this.queryParams.createBy = this.$store.getters.name
      }
      // console.log(this.queryParams)
      // console.log(token)
      this.queryParams.id = this.$route.query.id
      cmsListMessage(this.queryParams).then(response => {
        // console.log(response)
        for (let i = 0; i < response.rows.length; i++) {
          let mesInfo = response.rows[i]
          /* if (mesInfo.avatar != null && mesInfo.avatar !== "") {
            response.rows[i].avatar = process.env.VUE_APP_BASE_API + mesInfo.avatar
          } */
          if (mesInfo.children != null && mesInfo.children !== '') {
            for (let j = 0; j < response.rows[i].children.length; j++) {
              let children = response.rows[i].children
              if (children.avatar != null && children.avatar !== '') {
                response.rows[i].children[j].avatar = process.env.VUE_APP_BASE_API + children.avatar
              }
            }

          }
        }

        this.messageList = response.rows
        this.total = response.total
      })
    },
    blur(e) {
      this.cursorIndexStart = e.srcElement.selectionStart  // 获取input输入框失去焦点时光标选中开始的位置
      this.cursorIndexEnd = e.srcElement.selectionEnd  // 获取input输入框失去焦点时光标选中结束的位置
    },
    output(val) {
      if (this.cursorIndexStart !== null && this.messageForm.content) {
        //如果 文本域获取了焦点, 则在光标位置处插入对应字段内容
        this.messageForm.content = this.messageForm.content.substring(0, this.cursorIndexStart) + val + this.messageForm.content.substring(this.cursorIndexEnd)
      } else {
        // 如果 文本域未获取焦点, 则在字符串末尾处插入对应字段内容
        this.messageForm.content = this.messageForm.content ? this.messageForm.content : '' + val
      }
    },
    //跳转到相应位置
    to() {
      if (this.$route.query.id != null) {
        var toEl = document.getElementById(this.$route.query.id)
        if (toEl != null) {
          if (toEl != null && toEl != '') {
            // toEl 为指定跳转到该位置的DOM节点
            let bridgeCms = toEl
            let bodyTop = document.body
            let heightCms = 0
            // 计算该 DOM 节点到 bodyTop 顶部距离
            do {
              heightCms += bridgeCms.offsetTop
              bridgeCms = bridgeCms.offsetParent
            } while (bridgeCms !== bodyTop)
            // 滚动到指定位置
            window.scrollTo({
              top: heightCms,
              behavior: 'smooth'
            })
          }
        }
      }
    }

  }
}
</script>

<style scoped>
.elementCollapse {
  width: 98%;
  height: 100%;
  margin: 0 auto;
  padding-top: 0.1rem;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.collapseBtn {
  width: 100%;
  height: 2vh;
  line-height: 2vh;
  text-align: center;
  font-size: 12px;
  color: #000;
  cursor: pointer;
}

.collapseHeaderBox {
  height: calc(100% - 2vh);
}

.collapseHeader {
  background-color: #fff;
}

.collapseBox {
  margin-top: 1vh;
  flex: 1;
}

.collapseBoxMain {
  width: 100%;
}

.publish {
  margin-bottom: 20px;
}

.author {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  width: 100%;
  margin-bottom: 20px;
}

.nkname {
  margin: 10px;
  max-width: 530px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
